package com.mine.yyb.modules.sys.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mine.yyb.common.utils.exception.MineErrorCode;
import com.mine.yyb.common.utils.exception.MineException;
import com.mine.yyb.common.utils.json.MineJacksonkMapper;
import com.mine.yyb.common.web.YybBaseController;
import com.mine.yyb.modules.sys.bo.UserBO;
import com.mine.yyb.modules.sys.enums.SysCodeEnum;
import com.mine.yyb.modules.sys.enums.UserRoleEnum;
import com.mine.yyb.modules.sys.service.IUserService;
import com.mine.yyb.modules.sys.vo.UserVO;

/**
 * <pre>
 * <一句话功能简述>
 * 
 * 通用Controller，处理登录、退出、进入首页等相关请求
 * 
 * <功能详细描述>
 * </pre>
 * 
 * @author xuganhua
 * @version [版本号, 2016年5月21日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
public class CommonControl extends YybBaseController
{
    @Autowired
    private IUserService iUserService;
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 进入登录页面
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年5月21日]
     * @param request
     * @param response
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/initLoginPage")
    public String initLogin(HttpServletRequest request, HttpServletResponse response)
    {
        getResponseHeader(response);
        return "/login";
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 普通用户登录
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2015年12月21日]
     * @param request
     * @param userBO
     * @return
     * @throws MineException
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/login")
    public ResponseEntity<String> login(HttpServletRequest request, @ModelAttribute UserBO userBO)
        throws MineException
    {
        boolean result = false;// 表示登录验证不通过
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", result);
        try
        {
            logger.info(userBO.toString());
            // 判断用户名是否为空
            if (StringUtils.isBlank(userBO.getUsername()))
            {
                throw new MineException(SysCodeEnum.ERROR_USERNAME_BLANK);
            }
            // 判断密码是否为空
            if (StringUtils.isBlank(userBO.getPassword()))
            {
                throw new MineException(SysCodeEnum.ERROR_PASSWORD_BLANK);
            }
            userBO.setRole(UserRoleEnum.USER_NORMAL_ROLE.getRole());
            UserVO userVO = iUserService.queryTheUser(userBO);
            if (userVO != null)
            {
                result = true;
                map.put("valid", result);
                request.getSession().setAttribute("userToken", userVO);
            }
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(MineJacksonkMapper.convertObjectToString(map), responseHeaders,
            HttpStatus.OK);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 进入系统首页面
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年5月21日]
     * @param request
     * @param response
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/initHomePage")
    public String initHomePage(HttpServletRequest request, HttpServletResponse response)
    {
        getResponseHeader(response);
        return "/html/home";
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 进入密码找回页面
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年5月23日]
     * @param request
     * @param response
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/initRecoveryPage")
    public String initRecoveryPage(HttpServletRequest request, HttpServletResponse response)
    {
        getResponseHeader(response);
        return "/recovery";
    }
    
    @RequestMapping(value = "/checkEmailExist")
    public ResponseEntity<String> checkEmailExistTo(HttpServletRequest request, @ModelAttribute UserBO userBO)
        throws MineException
    {
        boolean result = false;// 表示邮箱已经存在
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", result);
        try
        {
            logger.info(userBO.toString());
            
            // 判断邮箱是否为空
            if (StringUtils.isBlank(userBO.getEmail()))
            {
                throw new MineException(SysCodeEnum.ERROR_EMAIL_BLANK);
            }
            
            result = iUserService.isEmailExist(userBO);
            map.put("valid", result);
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(MineJacksonkMapper.convertObjectToString(map), responseHeaders,
            HttpStatus.OK);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 验证密码是否正确
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年1月18日]
     * @param request
     * @param userBO
     * @return
     * @throws MineException
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/checkPwd")
    public ResponseEntity<String> checkPwd(HttpServletRequest request, @ModelAttribute UserBO userBO)
        throws MineException
    {
        boolean result = false;// 表示登录验证不通过
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", result);
        
        try
        {
            logger.info(userBO.toString());
            
            // 判断内部ID是否为空
            if (StringUtils.isBlank(userBO.getInnerID()))
            {
                throw new MineException(SysCodeEnum.ERROR_INNERID_BLANK);
            }
            
            // 判断旧密码是否为空
            if (StringUtils.isBlank(userBO.getPassword()))
            {
                throw new MineException(SysCodeEnum.ERROR_OLD_PWD_ERROR);
            }
            
            userBO.setRole(UserRoleEnum.USER_NORMAL_ROLE.getRole());
            UserVO userVO = iUserService.queryTheUser(userBO);
            if (userVO != null)
            {
                result = true;
                map.put("valid", result);
            }
            else
            {
                result = false;
                map.put("valid", result);
            }
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(MineJacksonkMapper.convertObjectToString(map), responseHeaders,
            HttpStatus.OK);
    }
    
    /**
     * <一句话功能简述></br>
     *
     * <功能详细描述></br>
     * 
     * @param request
     * @param userBO
     * @return
     * @throws MineException
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/checkAdminPwd")
    public ResponseEntity<String> checkAdminPwd(HttpServletRequest request, @ModelAttribute UserBO userBO)
        throws MineException
    {
        boolean result = false;// 表示登录验证不通过
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", result);
        
        try
        {
            logger.info(userBO.toString());
            
            // 判断内部ID是否为空
            if (StringUtils.isBlank(userBO.getInnerID()))
            {
                throw new MineException(SysCodeEnum.ERROR_INNERID_BLANK);
            }
            
            // 判断旧密码是否为空
            if (StringUtils.isBlank(userBO.getPassword()))
            {
                throw new MineException(SysCodeEnum.ERROR_OLD_PWD_ERROR);
            }
            
            userBO.setRole(UserRoleEnum.USER_ADMIN_ROLE.getRole());
            UserVO userVO = iUserService.queryTheUser(userBO);
            if (userVO != null)
            {
                result = true;
                map.put("valid", result);
            }
            else
            {
                result = false;
                map.put("valid", result);
            }
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(MineJacksonkMapper.convertObjectToString(map), responseHeaders,
            HttpStatus.OK);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 修改密码
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年1月18日]
     * @param request
     * @param userBO
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "changePwd")
    public ResponseEntity<String> changePwd(HttpServletRequest request, @ModelAttribute UserBO userBO)
    {
        // 响应码
        String retCode = null;
        try
        {
            logger.info(userBO.toString());
            
            // 判断内部ID是否为空
            if (StringUtils.isBlank(userBO.getInnerID()))
            {
                throw new MineException(SysCodeEnum.ERROR_INNERID_BLANK);
            }
            
            // 判断新密码是否为空
            if (StringUtils.isBlank(userBO.getNewPwd()))
            {
                throw new MineException(SysCodeEnum.ERROR_PASSWORD_BLANK);
            }
            
            retCode = iUserService.changeUserPwd(userBO);
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
            retCode = e.getErrorCode().name();
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
            retCode = MineErrorCode.ERROR_INTERNAL.name();
        }
        return getResponseEntity(retCode);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 进入管理员登录页面
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年5月21日]
     * @param request
     * @param response
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/initAdminLoginPage")
    public String initAdminLoginPage(HttpServletRequest request, HttpServletResponse response)
    {
        getResponseHeader(response);
        return "/admin";
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 管理员用户登录
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2015年12月30日]
     * @param request
     * @param userBO
     * @return
     * @throws MineException
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/admin")
    public ResponseEntity<String> loginAdmin(HttpServletRequest request, @ModelAttribute UserBO userBO)
        throws MineException
    {
        boolean result = false;// 表示登录验证不通过
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", result);
        
        try
        {
            logger.info(userBO.toString());
            
            // 判断用户名是否为空
            if (StringUtils.isBlank(userBO.getUsername()))
            {
                throw new MineException(SysCodeEnum.ERROR_USERNAME_BLANK);
            }
            
            // 判断密码是否为空
            if (StringUtils.isBlank(userBO.getPassword()))
            {
                throw new MineException(SysCodeEnum.ERROR_PASSWORD_BLANK);
            }
            userBO.setRole(UserRoleEnum.USER_ADMIN_ROLE.getRole());
            UserVO userVO = iUserService.queryTheUser(userBO);
            if (userVO != null)
            {
                result = true;
                map.put("valid", result);
                request.getSession().setAttribute("userToken", userVO);
            }
        }
        catch (MineException e)
        {
            logger.error(e.getErrorCode().name(), e);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(MineJacksonkMapper.convertObjectToString(map), responseHeaders,
            HttpStatus.OK);
    }
    
    /**
     * <pre>
     * <一句话功能简述>
     * 
     * 进入登录页面
     * 
     * <功能详细描述>
     * </pre>
     *
     * @author xuganhua
     * @version [版本号, 2016年5月21日]
     * @param request
     * @param response
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping(value = "/initManagerPage")
    public String initManagerPage(HttpServletRequest request, HttpServletResponse response)
    {
        getResponseHeader(response);
        return "/html/manager";
    }
    
}
